package com.link.play.fit.ai.utils

import com.link.play.fit.ai.bean.ControlDayData
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.utils.DateEx.getCurrentDayOfMonth
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException
import java.time.temporal.ChronoUnit
import java.util.Calendar
import java.util.Locale
import java.util.TimeZone


object TimeUtils {
    /**
     * 将 "HH:mm:ss:a" 格式的时间转换为当日时间戳
     * 示例输入："09:22:AM" → 转换为当天 09:22 AM 的时间戳
     */
    fun convertToDailyTimestamp(timeStr: String): Long {
        return try {
            // 预处理字符串（适配非标准格式）
            val formattedTime = timeStr
                .replace(":AM", " AM")
                .replace(":PM", " PM")

            val sdf = SimpleDateFormat("hh:mm a", Locale.US).apply {
                timeZone = TimeZone.getDefault()
            }

            val parsedDate = sdf.parse(formattedTime) ?: return -1

            // 结合当前日期
            Calendar.getInstance().apply {
                timeInMillis = System.currentTimeMillis()
                set(Calendar.HOUR_OF_DAY, parsedDate.hours)
                set(Calendar.MINUTE, parsedDate.minutes)
                set(Calendar.SECOND, 0)
                set(Calendar.MILLISECOND, 0)

                // 如果时间已过今天，设置为明天
                if (timeInMillis <= System.currentTimeMillis()) {
                    add(Calendar.DAY_OF_YEAR, 1)
                }
            }.timeInMillis
        } catch (e: Exception) {
            -1
        }
    }

    fun isAverageAfter1130AM(timeList: List<String>?): Boolean {
        if (timeList.isNullOrEmpty()) {
            return false
        }

        var totalMinutes = 0
        for (time in timeList) {
            val parts = time.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            require(parts.size == 3) { "无效的时间格式: $time" }
            var hour = parts[0].toInt()
            val minutes = parts[1].toInt()
            val period = parts[2].uppercase(Locale.getDefault()) // 确保处理大写

            if ("PM" == period) {
                if (hour != 12) {
                    hour += 12
                }
            } else if ("AM" == period) {
                if (hour == 12) {
                    hour = 0
                }
            } else {
                throw IllegalArgumentException("无效的时段: $period")
            }

            totalMinutes += hour * 60 + minutes
        }

        val average = totalMinutes.toDouble() / timeList.size
        return average > 690 // 11:30 AM对应690分钟
    }

    fun pmToLocalTime(timeString: String): LocalTime {
        try {
            val formattedTime = timeString
                .replace(":AM", " AM")
                .replace(":PM", " PM")

            // 定义时间格式（注意使用 Locale 确保正确解析 AM/PM）
            val formatter = DateTimeFormatter.ofPattern("h:mm a")
                .withLocale(java.util.Locale.ENGLISH) // 明确指定英文环境
            // 解析字符串为 LocalTime
            val localTime = LocalTime.parse(formattedTime, formatter)


            // 3. 格式化为 24 小时制的字符串（例如 "00:13"）
            val formatter24h = DateTimeFormatter.ofPattern("HH:mm")
            localTime.format(formatter24h)

            return localTime
        } catch (e: DateTimeParseException) {
            println("解析失败: ${e.message}")
        }
        return LocalTime.now()
    }

    fun getDateRange(startDateStr: String?, endDateStr: String?, day: Int): List<ControlDayData> {
        val dateList: MutableList<ControlDayData> = ArrayList()
        val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())

        try {
            // 参数非空校验
            if (startDateStr.isNullOrEmpty() || endDateStr.isNullOrEmpty()) {
                return ArrayList()
            }

            // 解析开始和结束日期
            val startDate = sdf.parse(startDateStr)
            val endDate = sdf.parse(endDateStr)

            val startCalendar = Calendar.getInstance().apply {
                time = startDate
                resetCalendarTime(this) // 重置时间为00:00:00
            }

            val endCalendar = Calendar.getInstance().apply {
                time = endDate
                resetCalendarTime(this) // 重置时间为00:00:00
            }

            // 确保开始日期 <= 结束日期
            if (startCalendar.after(endCalendar)) {
                return ArrayList() // 或交换日期: Collections.swap(startCalendar, endCalendar)
            }

            var index = 1
            val tempCalendar = startCalendar.clone() as Calendar


            // 生成日期列表
            run {
                while (!tempCalendar.after(endCalendar)) {
                    if (dateList.size > day) return@run
                    if (isDateAfterToday(sdf.format(tempCalendar.time))) return@run
                    dateList.add(
                        ControlDayData(
                            timeDay = sdf.format(tempCalendar.time),
//                            timeValue = if (index == 1) "${index}st" else if (index == 2) "${index}nd" else if (index == 3) "${index}rd" else "${index}th",

                            timeValue = "Day $index",
                            isAfter = isDateAfterToday(sdf.format(tempCalendar.time))
                        )
                    )
                    tempCalendar.add(Calendar.DATE, 1)
                    index += 1
                }
            }


            // 标记最后一个元素的当前位置
            if (dateList.isNotEmpty()) {
                val k = dateList.indexOfFirst { it.timeDay == getCurrentDayOfMonth() }
                if (k != -1) {
                    dateList[k].currentPosition = k
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            return ArrayList()
        }

        return dateList
    }


    private fun resetCalendarTime(calendar: Calendar) {
        calendar[Calendar.HOUR_OF_DAY] = 0
        calendar[Calendar.MINUTE] = 0
        calendar[Calendar.SECOND] = 0
        calendar[Calendar.MILLISECOND] = 0
    }

    fun completeControlDays(original: List<ControlDayData>): List<ControlDayData> {
        if (original.isEmpty()) return original

        val currentSize = original.size
        val targetSize = getNextThreshold(currentSize)
        if (targetSize <= currentSize) return original

        // 获取最后一个元素的日期和数值
        val lastItem = original.last()
        var currentDate = LocalDate.parse(lastItem.timeDay, DateTimeFormatter.ISO_DATE)
        var currentValue = lastItem.timeValue.replace("th", "").replace("st", "").replace("nd", "")
            .replace("rd", "") .replace("Day ", "").toInt()

        // 生成补全数据
        return original.toMutableList().apply {
            repeat(targetSize - currentSize) {
                currentDate = currentDate.plusDays(1)
                currentValue++
//                if (isDateAfterToday(currentDate.format(DateTimeFormatter.ISO_DATE))) { //是否是今天之后的日期
//                    add(
//                        ControlDayData(
//                            timeDay = currentDate.format(DateTimeFormatter.ISO_DATE),
////                            timeValue = if (currentValue == 1) "${currentValue}st" else if (currentValue == 2) "${currentValue}nd" else if (currentValue == 3) "${currentValue}rd" else "${currentValue}th",
//                            timeValue = "Day $currentValue",
//
//                            isAfter = true
//                        )
//                    )
//                } else {
                    if (currentDate.format(DateTimeFormatter.ISO_DATE) == getCurrentDayOfMonth()) { //是否是当天
                        add(
                            ControlDayData(
                                timeDay = currentDate.format(DateTimeFormatter.ISO_DATE),
                                timeValue = "Day $currentValue",
                                isAfter = false,
                                currentPosition = currentValue - 1
                            )
                        )
                    } else {
                        add(
                            ControlDayData(
                                timeDay = currentDate.format(DateTimeFormatter.ISO_DATE),
                                timeValue = "Day $currentValue",
                                isAfter = false
                            )
                        )
                    }

//                }

            }
        }
    }

    private fun getNextThreshold(current: Int): Int {
        return when {
            current < 7 -> 7
            current < 14 -> 14
            current < 21 -> 21
            current < 28 -> 28
            current < 30 -> 30
            else -> current
        }
    }

    fun findIndexByDate(targetDate: String, dataList: List<ControlDayData>): Int {
        dataList.forEachIndexed { index, item ->
            if (item.timeDay == targetDate) {
                return index
            }
        }
        return -1 // 未找到时返回-1
    }


    fun calculateEndDate(dateString: String, mode: String): String? {
        val DATE_PATTERN = "yyyy-MM-dd"
        val dateFormat = SimpleDateFormat(DATE_PATTERN, Locale.getDefault())
        return try {
            // 解析输入日期
            val calendar = Calendar.getInstance().apply {
                time = dateFormat.parse(dateString) ?: return null
            }

            // 根据模式进行计算
            when (mode.lowercase(Locale.ROOT)) {
                "year" -> calendar.add(Calendar.YEAR, 1)
                "week" -> calendar.add(Calendar.DAY_OF_YEAR, 7)
                else -> return null
            }

            // 格式化输出
            dateFormat.format(calendar.time)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    // 获取订阅周期时长（需预先定义商品周期）
    fun getSubscriptionPeriodMillis(productId: String): Long {
        return when (productId) {
            "week" -> 7L * 24 * 60 * 60 * 1000 // 7 天
            "year" -> 365L * 24 * 60 * 60 * 1000 // 1 年
            else -> throw IllegalArgumentException("Unknown subscription")
        }
    }

    fun isDateAfterToday(dateStr: String): Boolean {
        // 定义日期格式（支持 "yyyy-MM-dd" 格式）
        val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")

        // 解析字符串为 LocalDate 对象
        val inputDate = try {
            LocalDate.parse(dateStr, formatter)
        } catch (e: Exception) {
            // 处理无效日期格式
            return false
        }

        // 获取当前日期（系统时区）
        val today = LocalDate.now()

        // 比较日期是否在今天之后
        return inputDate.isAfter(today)
    }

    fun calculateEndTime(startTime: String, type: String): String? {
       val sdf = SimpleDateFormat("HH:mm", Locale.getDefault())
        return try {
            // 1. 验证输入类型
            val hoursToAdd = when (type) {
                "+8" -> 8
                "+10" -> 10
                "+12" -> 12
                else -> return null
            }

            // 2. 解析时间
            val date = sdf.parse(startTime) ?: return null

            // 3. 计算新时间
            val calendar = Calendar.getInstance().apply {
                time = date
                add(Calendar.HOUR_OF_DAY, hoursToAdd)
            }

            // 4. 格式化输出
            sdf.format(calendar.time)
        } catch (e: Exception) {
            null
        }
    }

    fun calculateFinalTime(inputTime: String, offset: String): String {
        if(inputTime.isEmpty()) return ""
        // 拆分输入时间
        val parts = inputTime.split(":")
        require(parts.size == 3) { "Invalid time format. Expected HH:mm:AM/PM" }

        // 解析小时、分钟、AM/PM
        val originalHour = parts[0].toInt()
        val originalMinute = parts[1].toInt()
        val period = parts[2].uppercase()

        // 转换为 24 小时制
        var hour24 = when (period) {
            "AM" -> if (originalHour == 12) 0 else originalHour
            "PM" -> if (originalHour == 12) 12 else originalHour + 12
            else -> throw IllegalArgumentException("Invalid AM/PM value")
        }

        // 计算总分钟数并应用偏移
        val totalMinutes = hour24 * 60 + originalMinute + when (offset) {
            "+8" -> 8 * 60
            "+10" -> 10 * 60
            "+12" -> 12 * 60
            else -> throw IllegalArgumentException("Invalid offset. Use +8, +10, +12")
        }

        // 处理跨天并转换回小时和分钟
        val adjustedMinutes = totalMinutes % (24 * 60)
        val adjustedHour24 = adjustedMinutes / 60
        val adjustedMinute = adjustedMinutes % 60

        // 转换回 12 小时制
        val (hour12, periodAdjusted) = when (adjustedHour24) {
            0 -> 12 to "AM"
            in 1..11 -> adjustedHour24 to "AM"
            12 -> 12 to "PM"
            else -> (adjustedHour24 - 12) to "PM"
        }

        return "%02d:%02d:%s".format(hour12, adjustedMinute, periodAdjusted)
    }
    fun convertTo24Hour(timeStr: String): String {
        if(timeStr.isEmpty()) return ""
        // 分割字符串为 [小时, 分钟, 时段]
        val parts = timeStr.split(":")
        require(parts.size == 3) { "时间格式错误，应使用 'HH:mm:AM/PM'" }

        // 提取并验证各部分
        val hour = parts[0].toIntOrNull() ?: throw IllegalArgumentException("小时无效")
        val minute = parts[1]
        val period = parts[2].uppercase()

        require(hour in 1..12) { "小时应在 1-12 之间" }
        require(period == "AM" || period == "PM") { "时段需为 AM 或 PM" }

        // 转换为 24 小时制小时
        val convertedHour = when (period) {
            "AM" -> if (hour == 12) 0 else hour
            "PM" -> if (hour == 12) 12 else hour + 12
            else -> throw IllegalStateException("不可达代码")
        }

        // 组合结果（补零处理）
        return "%02d:%s".format(convertedHour, minute)
    }

    fun calculateDaysBetween(startDateStr: String, endDateStr: String): Long {
        if(startDateStr.isEmpty() || endDateStr.isEmpty()) return 0
        // 定义日期格式
        val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")

        // 解析字符串为日期对象
        val startDate = LocalDate.parse(startDateStr, formatter)
        val endDate = LocalDate.parse(endDateStr, formatter)

        // 计算天数差
        return ChronoUnit.DAYS.between(startDate, endDate)
    }

}